from django.contrib.auth.backends import ModelBackend
import re
from users.models import User


class MyAuthenticateBackend(ModelBackend):
    """此类作用是继承系统auth认证，通过类继承覆盖自证系统逻辑，重写类方法
    实现多账号登录  用户名和手机充当 账号登录
    如需需要email 登录继续写即可
    """

    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            # 判断用户名是否是手机号
            if re.match(r'^1[3-9]\d{9}$', username):
                user = User.objects.get(phone=username)
            # 通过用户名查找账号
            else:
                user = User.objects.get(username=username)
        except User.DoesNotExist:
            return None
        else:
            if not user.check_password(password):
                return None
            return user
